<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的课表 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .semester-selector {
            display: flex;
            align-items: center;
        }

        .semester-selector label {
            margin-right: 10px;
            color: #555;
            font-weight: 500;
        }

        .semester-selector select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .schedule-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .day-section {
            margin-bottom: 25px;
        }

        .day-header {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 2px solid #f0f0f0;
            color: #2c3e50;
        }

        .course-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .course-item {
            display: flex;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 6px;
            background-color: #f9f9f9;
            border-left: 4px solid #3498db;
        }

        .course-item.type-required {
            border-left-color: #3498db;
        }

        .course-item.type-elective {
            border-left-color: #27ae60;
        }

        .course-item.type-general {
            border-left-color: #f39c12;
        }

        .course-time {
            width: 120px;
            font-weight: 500;
            color: #555;
        }

        .course-details {
            flex: 1;
        }

        .course-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .course-info {
            display: flex;
            flex-wrap: wrap;
            font-size: 14px;
            color: #666;
        }

        .course-info span {
            margin-right: 15px;
            margin-bottom: 5px;
        }

        .empty-schedule {
            text-align: center;
            padding: 50px;
            color: #777;
            font-size: 16px;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }

        .course-type-legend {
            display: flex;
            margin-bottom: 20px;
            gap: 20px;
        }

        .legend-item {
            display: flex;
            align-items: center;
        }

        .legend-color {
            width: 15px;
            height: 15px;
            margin-right: 5px;
        }

        .legend-required {
            background-color: #3498db;
        }

        .legend-elective {
            background-color: #27ae60;
        }

        .legend-general {
            background-color: #f39c12;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span id="sidebar-student-name">学生</span> - <span th:text="${session.user.role}">学生</span>
                </div>
            </div>
            <ul class="menu">
                <li><a href="/student/dashboard">我的概览</a></li>
                <li><a href="/student/courses">选课中心</a></li>
                <li class="active"><a href="/student/schedule">我的课表</a></li>
                <li><a href="/student/grades">我的成绩</a></li>
                <li><a href="/student/profile">个人信息</a></li>
            </ul>
            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>我的课表</h1>
                <div class="semester-selector">
                    <label for="semester">学期:</label>
                    <select id="semester" name="semester" onchange="changeSemester()">
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上" selected>大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                </div>
            </div>

            <div class="course-type-legend">
                <div class="legend-item">
                    <div class="legend-color legend-required"></div>
                    <span>必修课</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color legend-elective"></div>
                    <span>选修课</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color legend-general"></div>
                    <span>公选课</span>
                </div>
            </div>

            <div class="schedule-container" id="scheduleContainer">
                <!-- 课表数据将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <script>
        // 页面加载时初始化课表
        document.addEventListener('DOMContentLoaded', function () {
            fetchStudentInfo();
            const currentSemester = document.getElementById('semester').value;
            fetchSchedule(currentSemester);
        });

        // 获取学生信息
        function fetchStudentInfo() {
            fetch('/api/student/info')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取学生信息失败') });
                    }
                    return response.json();
                })
                .then(student => {
                    // 更新侧边栏显示的学生姓名
                    document.getElementById('sidebar-student-name').textContent = student.name;

                    // 设置默认学期为学生当前年级
                    if (student.grade) {
                        document.getElementById('semester').value = student.grade;
                        fetchSchedule(student.grade);
                    }
                })
                .catch(error => {
                    console.error('获取学生信息出错:', error);
                });
        }

        // 切换学期
        function changeSemester() {
            const semester = document.getElementById('semester').value;
            fetchSchedule(semester);
        }

        // 获取课表数据
        function fetchSchedule(semester) {
            fetch(`/api/student/schedule?semester=${encodeURIComponent(semester)}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取课表失败') });
                    }
                    return response.json();
                })
                .then(courses => {
                    console.log("课程数据:", courses);
                    renderSchedule(courses);
                })
                .catch(error => {
                    console.error('获取课表出错:', error);
                });
        }

        // 日期顺序
        const dayOrder = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

        // 渲染课表
        function renderSchedule(courses) {
            const scheduleContainer = document.getElementById('scheduleContainer');

            if (!courses || courses.length === 0) {
                scheduleContainer.innerHTML = '<div class="empty-schedule">当前学期没有课程安排</div>';
                return;
            }

            // 按星期几分组课程
            const coursesByDay = {};
            dayOrder.forEach(day => {
                coursesByDay[day] = [];
            });

            // 填充分组
            courses.forEach(course => {
                if (course.class_day && dayOrder.includes(course.class_day)) {
                    coursesByDay[course.class_day].push(course);
                }
            });

            // 生成HTML
            let scheduleHtml = '';

            dayOrder.forEach(day => {
                const dayCourses = coursesByDay[day];

                // 如果这一天没有课，则跳过
                if (dayCourses.length === 0) {
                    return;
                }

                // 按时间排序当天课程
                dayCourses.sort((a, b) => {
                    if (a.start_time && b.start_time) {
                        return a.start_time.localeCompare(b.start_time);
                    }
                    return 0;
                });

                // 创建每天的课程列表
                scheduleHtml += `
                    <div class="day-section">
                        <div class="day-header">${day}</div>
                        <ul class="course-list">
                `;

                dayCourses.forEach(course => {
                    // 确定课程类型
                    let typeClass = 'type-required';
                    if (course.courseType === '选修课') {
                        typeClass = 'type-elective';
                    } else if (course.courseType === '公选课') {
                        typeClass = 'type-general';
                    }

                    // 准备时间信息
                    let timeInfo = "";
                    if (course.start_time && course.end_time) {
                        timeInfo = `${course.start_time.substring(0, 5)}-${course.end_time.substring(0, 5)}`;
                    }

                    // 准备教师信息
                    let teacherName = course.teacherId || '未知';
                    if (course.teacherName) {
                        teacherName = course.teacherName;
                    }

                    // 准备教室信息
                    let location = course.classroomId || '未知';
                    if (course.location_detail) {
                        location = course.location_detail;
                    }

                    // 准备周次信息
                    let weeksInfo = course.weeks || '1-16周';
                    if (!weeksInfo.endsWith('周')) {
                        weeksInfo += '周';
                    }

                    scheduleHtml += `
                        <li class="course-item ${typeClass}">
                            <div class="course-time">${timeInfo}</div>
                            <div class="course-details">
                                <div class="course-name">${course.courseName || course.name}</div>
                                <div class="course-info">
                                    <span>教师：${teacherName}</span>
                                    <span>教室：${location}</span>
                                    <span>周次：${weeksInfo}</span>
                                    <span>学分：${course.credit || 0}</span>
                                </div>
                            </div>
                        </li>
                    `;
                });

                scheduleHtml += `
                        </ul>
                    </div>
                `;
            });

            scheduleContainer.innerHTML = scheduleHtml;
        }
    </script>
</body>

</html>